package tech.ezrealc.fall2023.service;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.ezrealc.fall2023.exception.AuthenticationFailedException;
import tech.ezrealc.fall2023.model.session.SessionDO;
import tech.ezrealc.fall2023.model.session.SessionDTO;
import tech.ezrealc.fall2023.model.session.SessionQuery;
import tech.ezrealc.fall2023.model.user.UserDTO;
import tech.ezrealc.fall2023.repository.SessionRepository;
import tech.ezrealc.fall2023.repository.UserRepository;

import java.math.BigInteger;
import java.util.UUID;

@Service
@Transactional
@Slf4j
public class SessionService {

    @Resource
    private SessionRepository sessionRepository;

    @Resource
    private UserRepository userRepository;

    public SessionDTO authenticate(SessionQuery sessionQuery) throws AuthenticationFailedException {
        SessionDTO sessionDTO = new SessionDTO();

        UserDTO userDTO = userRepository.authenticate(sessionQuery.getEmail(), sessionQuery.getPassword());
        if (userDTO == null) {
            throw new AuthenticationFailedException("用户名或密码错误");
        }
        sessionDTO.setUser(userDTO.getId());

        SessionDO sessionDO = sessionRepository.findById(sessionDTO.getUser());
        if (sessionDO != null) {
            sessionDTO.setToken(sessionDO.getToken());
        }else {
            sessionDTO.setToken(String.valueOf(UUID.randomUUID()));
            sessionRepository.insertSession(sessionDTO);
        }

        log.info(sessionDTO.toString());

        return sessionDTO;
    }

    public boolean deAuthenticate(String token) {
        try {
            if (1 != sessionRepository.deleteSessionByToken(token)){
                throw new RuntimeException("删除失败");
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    public boolean verifyToken(String token) {
        return 1 == sessionRepository.hasRecord(token).get("count");
    }

}
